package com.xjtu.platform.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xjtu.platform.common.dao.CommonDao;
import com.xjtu.platform.common.entity.PenaltyTime;
import com.xjtu.platform.common.page.QueryAction;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;


import com.sun.mail.util.MailSSLSocketFactory;
import com.xjtu.platform.common.page.QueryAction2;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class Utils {


    public static <T> Map<String, Object> getPage(PageParam pageParam, QueryAction<T> queryAction) {
        //执行映射器方法之前立即执行分页参数（页码和每页记录数）的设置
        PageHelper.startPage(pageParam);

        List<T> list = queryAction.execute();
//        PageInfo<T> page2 = (PageInfo<T>) list;
//        System.out.println("获取的list的总数为: "+page2.getTotal());

        //执行映射器方法之后，立即执行PageInfo对象的创建
        PageInfo<T> pageInfo = new PageInfo<T>(list);


        Map<String, Object> page = new HashMap<>();
        page.put("current", pageInfo.getPageNum());//当前页
        page.put("pageSize", pageInfo.getPageSize());//每页最大记录数
        page.put("total", pageInfo.getTotal());//总记录数
        page.put("pages", pageInfo.getPages());//总页数
        page.put("size", pageInfo.getSize());//当前页实际记录数
        page.put("list", pageInfo.getList());//当前页的数据记录
        page.put("first", 1);
        page.put("pre", pageInfo.getPrePage());
        page.put("next", pageInfo.getNextPage());
        page.put("last", pageInfo.getPages());

        return page;

    }

    public static <T> Map<String, Object> getPage2(PageParam pageParam, QueryAction2<T> queryAction) {
        //执行映射器方法之前立即执行分页参数（页码和每页记录数）的设置
        PageHelper.startPage(pageParam);

        PageInfo<T> pageInfo = queryAction.execute();
//        System.out.println("获取的list的总数为: "+page2.getTotal());

        //执行映射器方法之后，立即执行PageInfo对象的创建
//        PageInfo<T> pageInfo = new PageInfo<T>(page2.getList());


        Map<String, Object> page = new HashMap<>();
        page.put("current", pageInfo.getPageNum());//当前页
        page.put("pageSize", pageInfo.getPageSize());//每页最大记录数
        page.put("total", pageInfo.getTotal());//总记录数
        page.put("pages", pageInfo.getPages());//总页数
        page.put("size", pageInfo.getSize());//当前页实际记录数
        page.put("list", pageInfo.getList());//当前页的数据记录
        page.put("first", 1);
        page.put("pre", pageInfo.getPrePage());
        page.put("next", pageInfo.getNextPage());
        page.put("last", pageInfo.getPages());

        return page;

    }


    /**
     * 将一个Java对象转换为json串，并向浏览器（客户端）输出
     *
     * @param resp 响应对象
     * @param obj  需要转化为json串的java对象
     * @throws IOException
     */

    public static void outJson(HttpServletResponse resp, Object obj) throws IOException {
        //json格式的媒体标准：application/json
        resp.setContentType("application/json;charset=UTF-8");//设置字符编码
        PrintWriter out = resp.getWriter();//获取向客户端发送字符信息流对象
        // 将list集合对象转化为json格式字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(obj);
        out.print(jsonString);

        out.flush();
        out.close();
    }

    public static void sendMail(String targetmail, String content) throws Exception {

        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");  //设置邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议SMTP
        prop.setProperty("mail.smtp.auth", "true"); // 验证用户名密码

        // 邮箱设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);


        //创建定义整个应用程序所需的环境信息的 Session 对象

        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("2014894101@qq.com", "rtyhrwledlliehgb");
            }
        });


        //开启Session的debug模式，可以查看到程序发送Email的运行过程
        session.setDebug(true);

        //通过session得到transport对象
        Transport ts = session.getTransport();

        //使用邮箱的用户名和授权码连上邮件服务器，这里使用已完成POP3\SMTP授权的我的账号
        ts.connect("smtp.qq.com", "2014894101@qq.com", "rtyhrwledlliehgb");

        //创建邮件对象
        MimeMessage message = new MimeMessage(session);

        //指明邮件的发件人
        message.setFrom(new InternetAddress("2014894101@qq.com"));

        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(targetmail));

        //邮件的标题
        message.setSubject("易心理");

        //邮件的文本内容,目前尚未尝试html格式
        message.setContent(content, "text/html;charset=UTF-8");

        //发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        ts.close();
    }

    public static String produceCode() {
        return String.valueOf(new Random().nextInt(900000) + 100000);
    }

//    public static void xlsFileExecutor(List<? extends Object> data, String[] header, String filename) {
//        System.out.println("正在生成 "+filename+" 的结案报告！");
//        String[] fieldNames = fieldName(data.get(0).getClass());
//        Workbook workbook = new HSSFWorkbook();
//        int rowSize = 0;
//        Sheet sheet = workbook.createSheet();
//        Row row = sheet.createRow(rowSize);
//        for (int i = 0; i < header.length; i++) {
//            row.createCell(i).setCellValue(header[i]);
//        }
//        try {
//            for (int x = 0; x < data.size(); x++) {
//                rowSize = 1;
//                Row rowNew = sheet.createRow(rowSize + x);
//                for (int i = 0; i < header.length; i++) {
//                    Object object = data.get(x);
//                    for (int i1 = 0; i1 < fieldNames.length; i1++) {
//                        String methodName = "get" + fieldNames[i].substring(0,             1).toUpperCase() + fieldNames[i].substring(1);//获取属性的get方法名
//                        Method method1 = object.getClass().getMethod(methodName);
//                        Object invoke = method1.invoke(object);//获取属性值
//                        rowNew.createCell(i).setCellValue(invoke.toString());
//                    }
//                }
//            }
//        } catch (Exception e) {
//
//        }
//        OutputStream outputStream = null;
//        try {
//            String pathhh=Constants.FILE_DIR+filename+".xls";
//            outputStream = new FileOutputStream(pathhh);
//            System.out.println("工具生成的文件在*"+pathhh);
//            workbook.write(outputStream);
//        } catch (Exception e) {
//
//        } finally {
//            try {
//                if (outputStream != null) {
//                    outputStream.flush();
//                    outputStream.close();
//                }
//            } catch (Exception e) {
//
//            }
//            try{
//                if(workbook != null){
//                    workbook.close();
//                }
//            } catch (Exception e){
//
//            }
//        }
//
//    }

//    static final String product = "Dysmsapi";
//    //产品域名,开发者无需替换
//    static final String domain = "dysmsapi.aliyuncs.com";
//    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
//    static final String accessKeyId = "LTAI5tGtEMnpXR3iEz5qLGci";
//    static final String accessKeySecret = "EzceC0y4zyi5UvEcnpyIKXRf2nCGao";
//
//    public static SendSmsResponse sendSms(String phone , String code) throws ClientException {
//        //可自助调整超时时间
//        try {
////            System.setProperty("sun.net.client.defaultConnectTimeout", "10");
////            System.setProperty("sun.net.client.defaultReadTimeout", "10");
//            //初始化acsClient,暂不支持region化
//            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
//            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
//            IAcsClient acsClient = new DefaultAcsClient(profile);
//
//            //组装请求对象-具体描述见控制台-文档部分内容
//            SendSmsRequest request = new SendSmsRequest();
//            //必填:待发送手机号
//            request.setPhoneNumbers(phone);
//            //必填:短信签名-可在短信控制台中找到
//            request.setSignName("阿里云短信测试");
//            //必填:短信模板-可在短信控制台中找到
////        request.setTemplateCode("SMS_152440521");
//            //SMS_154950909
//            request.setTemplateCode("SMS_154950909");
//            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//            request.setTemplateParam(code);
//
//            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//            //request.setSmsUpExtendCode("90997");
//
//            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//            //request.setOutId("yourOutId");
//
//            //hint 此处可能会抛出异常，注意catch
//            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
//            return sendSmsResponse;
//        } catch (ClientException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    private static String[] fieldName(Class clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        String[] fieldNames = new String[declaredFields.length];
        for (int i = 0; i < declaredFields.length; i++) {
            fieldNames[i] = declaredFields[i].getName(); //通过反射获取属性名
        }
        return fieldNames;
    }

    public static String transAddToUrl(String add) {
        return add.replaceAll(Constants.ADDRESS_HEAD, Constants.URL_HEAD);
    }

    public static String getTimeDifference(Timestamp startTime, Timestamp endTime) {
        LocalDateTime startDate = startTime.toLocalDateTime();
        LocalDateTime endDate = endTime.toLocalDateTime();

        // 计算时间差异
        long daysDifference = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println("差距的天数为:" + daysDifference);

        return Long.toString(daysDifference);
    }

    public static String calPenaltyMoney(String usingTime, CommonDao commonDao) {
        List<PenaltyTime> list = commonDao.getPenaltyRule();
        int day = Integer.parseInt(usingTime);
        int maxDay = 0;
        String money = "";
        for (PenaltyTime item : list) {
            int tempDay = Integer.parseInt(item.getDay());
            if (day >= tempDay && tempDay >= maxDay) {
                maxDay = tempDay;
                money = item.getPenalty_money();
            }
        }
        return money;
    }
}
